iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
自我挑戰組

Android kotlin &MVVM系列 第 22

Android學習筆記22

  • 分享至 

  • xImage
  •  

今天來綁定viewpager與tablayout
首先要建立一個viewpager的adapter

class MainPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
    var fragmentList: MutableList<Fragment> = ArrayList()
    var fragmentTitle: MutableList<String> = ArrayList()
    override fun getItem(position: Int): Fragment {
        return fragmentList[position]
    }

    override fun getCount(): Int {
        return fragmentList.size
    }

    fun addFragment(fragment: Fragment, title: String) {
        fragmentList.add(fragment)
        fragmentTitle.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragmentTitle[position]
    }
}

接著在activity

class FragmentActivity : BaseActiivity(){
    private val fragmentViewModel by lazy {
        initViewModel(application , FragmentViewModel::class.java)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityFragmentBinding>(this,R.layout.activity_fragment)
        binding.lifecycleOwner = this
        binding.viewmodel = fragmentViewModel
        val mainpagerAdapter = MainPagerAdapter(supportFragmentManager)
        mainpagerAdapter.addFragment(OneFragment(),"one")
        mainpagerAdapter.addFragment(TwoFragment(),"two")
        mainpagerAdapter.addFragment(ThreeFragment(),"three")
        binding.viewPager.adapter = mainpagerAdapter
        binding.viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(binding.TabLayout))
        binding.TabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                when (tab.position) {
                    0 -> binding.viewPager.currentItem = 0
                    1 -> binding.viewPager.currentItem = 1
                    3 -> binding.viewPager.currentItem = 2
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })

    }
}

上一篇
Android學習筆記21
下一篇
Android學習筆記23
系列文
Android kotlin &MVVM30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言